<template>
	<div class="system-menu-container">
		<el-card shadow="hover">
			<div class="btnStyle">
				<el-button type="success" icon="ele-Plus" @click="onOpenAddMenu">新增</el-button>
			</div>
			<el-table :data="dataList" style="width: 100%" row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
				<el-table-column label="资源名称" show-overflow-tooltip>
					<template #default="scope">
						<SvgIcon :name="scope.row.icon" />
						<span class="ml10">{{ $t(scope.row.name) }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="url" label="路由路径" show-overflow-tooltip></el-table-column>
				<el-table-column prop="terminal" width="100" column-key="1123" :show-overflow-tooltip="true" label="适用终端" :formatter="formatTerminal"/>
				<el-table-column prop="sysResource" width="100" column-key="1008" :show-overflow-tooltip="true" label="系统内资源" :formatter="formatTerminal"/>
				<el-table-column prop="perms" header-align="center" align="center" :show-overflow-tooltip="true" label="授权标识"/>
				<el-table-column prop="orderNum" label="排序" show-overflow-tooltip></el-table-column>
				<el-table-column prop="type" header-align="center" align="center" width="80" label="类型">
					<template #default="scope">
						<el-tag v-if="scope.row.type === 0">目录</el-tag>
						<el-tag v-else-if="scope.row.type === 1" type="success">菜单</el-tag>
						<el-tag v-else-if="scope.row.type === 2" type="info">按钮</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" show-overflow-tooltip width="140">
					<template #default="scope">
						<el-button type="primary" link @click="onOpenEditMenu(scope.row)">修改</el-button>
						<el-button type="primary" link @click="onTabelRowDel(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<el-dialog :close-on-click-modal="false" :title="!submitForm.id ? '新增' : '修改'" ref="addOrUpdate" v-model="addOrUpdateVisible">
			<el-form :model="submitForm" :rules="submitFormRule" ref="ruleFormRef" @keyup.enter.native="dataFormSubmit(ruleFormRef)" label-width="120px">
				<el-row>
					<el-col :span="24">
						<el-form-item label="上级资源" prop="parentId">
							<el-cascader :options="selectList"
										:props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'name' }"
										placeholder="请选择上级资源"
										clearable
										class="w100"
										v-model="submitForm.parentId">
										<template #default="{ node, data }">
											<span>{{ data.name }}</span>
											<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
										</template>
							</el-cascader>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="名称" prop="name">
							<el-input v-model="submitForm.name" placeholder="请输入资源名称" maxlength="50"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="别名" prop="alias">
							<el-input v-model="submitForm.alias" placeholder="请输入资源别名" maxlength="50"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="资源路径" prop="url">
							<el-input v-model="submitForm.url" placeholder="请输入资源路径：sys/menu" maxlength="150"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="授权标识" prop="perms">
							<el-input v-model="submitForm.perms" placeholder="多个用逗号分隔, 如: user:list,user:create" maxlength="50"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="资源类型" prop="type">
							<el-radio-group v-model="submitForm.type">
								<el-radio v-for="(type, index) in typeList" :label="index" :key="index">
								{{ type }}
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="图标" prop="perms">
							<IconSelector placeholder="请输入菜单图标" style="width:100%" v-model="submitForm.icon" type="all" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="排序" prop="orderNum">
							<el-input v-model="submitForm.orderNum" placeholder="排序" maxlength="4" min="0" max="9999" type="number"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="是否系统资源" prop="sysResource">
							<el-radio-group v-model="submitForm.sysResource">
								<el-radio v-for="(type, index) in dataDictionaryList['1008']" :label="index" :key="index">
								{{ type }}
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="终端" prop="terminal">
							<el-radio-group v-model="submitForm.terminal">
								<el-radio v-for="(type, index) in dataDictionaryList['1123']" :label="index" :key="index">
								{{ type }}
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="重定向" prop="redirect">
							<el-input v-model="submitForm.redirect" placeholder="资源为目录时必填" maxlength="100"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="是否隐藏" prop="isHide">
							<el-radio-group v-model="submitForm.isHide">
								<el-radio v-for="(type, index) in dataDictionaryList['1008']" :label="index" :key="index">
								{{ type }}
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="是否缓存" prop="isKeepAlive">
							<el-radio-group v-model="submitForm.isKeepAlive">
								<el-radio v-for="(type, index) in dataDictionaryList['1008']" :label="index" :key="index">
								{{ type }}
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="是否固定" prop="isAffix">
							<el-radio-group v-model="submitForm.isAffix">
								<el-radio v-for="(type, index) in dataDictionaryList['1008']" :label="index" :key="index">
								{{ type }}
								</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12">
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="addOrUpdateVisible = false">取消</el-button>
					<el-button type="primary" @click="dataFormSubmit(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, watch, onMounted, defineComponent } from 'vue'
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getCodeList } from '/@/utils/cacheDict'
import IconSelector from '/@/components/iconSelector/index.vue'
import {systemApi} from '/@/api/systemapi'
export default defineComponent({
	name: 'systemMenu',
	components: { IconSelector },
	setup() {
		const addMenuRef = ref();
		const editMenuRef = ref();
		const state = reactive({
			dataForm: {
				terminal: ''
			},
			istenant: import.meta.env.VITE_IS_TENANT,
			typeList: ['目录', '菜单', '按钮'],
			selectList: [],
			dataList: [],
			dataDictionaryList: {},
			submitForm: {
				id: '',
				parentId: '',
				name: '',
				alias: '',
				url: '',
				perms: '',
				type: 1,
				icon: '',
				orderNum: 0,
				sysResource: '1',
				tenantId: '',
				terminal: '',
				redirect: '',
				isHide: '0',
				isKeepAlive: '1',
				isAffix: '0'
			},
			submitFormRule: {
				parentId: { required: true, message: '请输入上级菜单', trigger: 'blur' },
				name: { required: true, message: '请输入租户名称', trigger: 'blur' },
				url: { required: true, message: '请输URL', trigger: 'blur' },
				type: { required: true, message: '请选择类型', trigger: 'blur' },
				sysResource: { required: true, message: '请选择是否系统内资源', trigger: 'blur' },
				tenantId: { required: true, message: '请选择租户', trigger: 'blur' },
				terminal: { required: true, message: '请选择终端类型', trigger: 'blur' },
				redirect: { required: false, message: '类型为目录时必须设置重定向', trigger: 'blur' },
				isHide: { required: true, message: '请选择是否隐藏', trigger: 'blur' },
				isKeepAlive: { required: true, message: '请选择是否缓存', trigger: 'blur' },
				isAffix: { required: true, message: '请选择是否固定', trigger: 'blur' }
			},
			addOrUpdateVisible: false
		});
		const ruleFormRef = ref<FormInstance>();
		watch(() => state.submitForm.type, (val:number) => {
			if(val === 0) {
				state.submitFormRule.redirect.required = true
			}else{
				state.submitFormRule.redirect.required = false
			}
		})
		// 获取 vuex 中的路由
		/* const menuTableData = computed(() => {
			return store.state.routesList.routesList;
		}); */
		// 页面加载时
		onMounted(() => {
			// 加载上级菜单
			getParentMenu();
			// 数据字典
			getCodeList(state, ['1008', '1123'])
			// 列表查询
			loadMenuList()
		})
		const getParentMenu = () => {
			systemApi().getMenuSelectList().then(data => {
				state.selectList = treeDataTranslate(data.menuList, 'id', 'parentId')
			})
		}
		const loadMenuList = () => {
			systemApi().getMenuList({'dataForm': state.dataForm}).then(data => {
				state.dataList = treeDataTranslate(data, 'id', 'parentId')
			})
		}
		const treeDataTranslate = (data:any, id = 'id', pid = 'parentId') => {
			var res:any = []
			var temp:any = {}
			for (var i = 0; i < data.length; i++) {
				temp[data[i][id]] = data[i]
			}
			for (var k = 0; k < data.length; k++) {
				if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
					if (!temp[data[k][pid]]['children']) {
						temp[data[k][pid]]['children'] = []
					}
					if (!temp[data[k][pid]]['_level']) {
						temp[data[k][pid]]['_level'] = 1
					}
					data[k]['_level'] = temp[data[k][pid]]._level + 1
					temp[data[k][pid]]['children'].push(data[k])
				} else {
					res.push(data[k])
				}
			}
			return res
		}
		// 打开新增菜单弹窗
		const onOpenAddMenu = () => {
			// addMenuRef.value.openDialog();
			state.submitForm = {
				id: '',
				parentId: '',
				name: '',
				alias: '',
				url: '',
				perms: '',
				type: 1,
				icon: '',
				orderNum: 0,
				sysResource: '1',
				tenantId: '',
				terminal: '',
				redirect: '',
				isHide: '0',
				isKeepAlive: '1',
				isAffix: '0'
			}
			state.addOrUpdateVisible = true
		};
		// 打开编辑菜单弹窗
		const onOpenEditMenu = (row:any) => {
			state.submitForm = {
				id: '',
				parentId: '',
				name: '',
				alias: '',
				url: '',
				perms: '',
				type: 1,
				icon: '',
				orderNum: 0,
				sysResource: '1',
				tenantId: '',
				terminal: '',
				redirect: '',
				isHide: '0',
				isKeepAlive: '1',
				isAffix: '0'
			}
			state.submitForm = row
			state.addOrUpdateVisible = true
			// ruleFormRef.value.resetFields()
		};
		const dataFormSubmit = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.validate((valid: boolean) => {
				if (valid) {
					// 提交数据
					const loading = ElLoading.service({
						lock: true,
						text: '处理中',
						background: 'rgba(0, 0, 0, 0.7)',
					})
					if(!state.submitForm.id) {
						// 新增
						systemApi().saveMenuInfo(state.submitForm).then((data) => {
							if (data && data.code === 0) {
								ElMessage.success('保存成功')
								// 加载上级菜单
								getParentMenu();
								// 列表查询
								loadMenuList()
								state.addOrUpdateVisible = false
							} else {
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('保存失败')
						}).finally(() => {
							loading.close()
						})
					} else{
						systemApi().updateMenuInfo(state.submitForm).then((data) => {
							if (data && data.code === 0) {
								ElMessage.success('保存成功')
								// 加载上级菜单
								getParentMenu();
								// 列表查询
								loadMenuList()
								state.addOrUpdateVisible = false
							} else {
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('保存失败')
						}).finally(() => {
							loading.close()
						})
					}
				}
			})
		}
		// 删除当前行
		const onTabelRowDel = (row: any) => {
			ElMessageBox.confirm(`此操作将永久删除资源, 是否继续?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				// 提交数据
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				systemApi().deleteMenuInfo(row.id).then(data => {
					if (data && data.code === 0) {
						ElMessage.success('删除成功');
						// 列表查询
						loadMenuList()
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error('删除失败')
				}).finally(() => {
					loading.close()
				})
			}).catch(() => {})
		}
		const formatTerminal = (row:any, column:any, cellValue:any, index:number) => {
			if (cellValue) {
				// return cellValue
				return state.dataDictionaryList[column.columnKey][cellValue]
			}
		}
		return {
			addMenuRef,
			editMenuRef,
			ruleFormRef,
			onOpenAddMenu,
			onOpenEditMenu,
			// menuTableData,
			onTabelRowDel,
			loadMenuList,
			treeDataTranslate,
			formatTerminal,
			dataFormSubmit,
			...toRefs(state),
		};
	},
});
</script>

<style scoped>

</style>